﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf;
using System.Drawing.Imaging;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;

namespace PdfWizard.UI.Services
{
    public class PdfCreatorService : IPdfCreatorService
    {
        private readonly IUnityContainer container;

        public PdfCreatorService(IUnityContainer container)
        {
            this.container = container;
        }

        #region IPdfCreatorService Members

        public void CreatePdf(string[] fileNames, string documentTitle, string outputPath, int compressionFactor)
        {
            CompressionService compressionService = ServiceLocator.Current.GetInstance<CompressionService>();

            if (compressionFactor < 0 || compressionFactor > 100)
                throw new ArgumentException(string.Format("Compression factor must be between 0 and 100. Actual value was '{0}'", compressionFactor));

            Document doc = new Document();
            doc.AddTitle(documentTitle);
            doc.SetPageSize(new Rectangle(2480, 3508));

            using (FileStream stream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, stream);
                writer.SetFullCompression();
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
                writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
                doc.Open();
                foreach (string fileName in fileNames)
                {
                    using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                    {
                        doc.Add(Image.GetInstance(container.Resolve<ICompressionService>().CompressImage(
                            fileStream, compressionFactor), ImageFormat.Jpeg));
                        fileStream.Close();
                    }
                }
                doc.Close();
                stream.Close();
            }
        }

        #endregion

        public CompressionService ServicesLocator { get; set; }
    }
}
